package com.sunrise.gateway.shiro.session;

import com.sunrise.gateway.commons.Constants;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * 待扩展的Session管理器
 **/
public class UserSessionManager extends DefaultWebSessionManager {
    private final static Logger LOGGER = LoggerFactory.getLogger(UserSessionManager.class);

    // 使一个request只获取一次session
    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
        HttpServletRequest sr = WebUtils.getHttpRequest(sessionKey);
        if (sr != null) {
            Object o = sr.getAttribute(Constants.SESSION_IN_REQUEST_NAME);
            if (o instanceof Session) {
                return (Session) o;
            }
        } else {
            LOGGER.error("不能从 SessionKey 获取到 ServletRequest");
        }

        Serializable sessionId = getSessionId(sessionKey);
        if (sessionId == null) {
            LOGGER.error("Unable to resolve session ID from SessionKey [" + sessionKey + "].");
            return null;
        }
        Session s = retrieveSessionFromDataSource(sessionId);
        if (!(s instanceof Session)) {
            String msg = "Could not find session with ID [" + sessionId + "]";
            throw new UnknownSessionException(msg);
        }
        if (sr != null) {
            sr.setAttribute(Constants.SESSION_IN_REQUEST_NAME, s);
        }
        return s;
    }
}
